import { useState, useEffect } from 'react'
import { Swiper, Toast, Grid, Button, SpinLoading, Input, Dialog } from 'antd-mobile'
import { LocationOutline, RightOutline } from 'antd-mobile-icons'
import styles from './Home.module.css'
import axios from '../../axios'
import { useNavigate } from 'react-router-dom'
import { QRCodeSVG } from 'qrcode.react';
import React, { useRef } from 'react';

const categories = [
  { icon: '🍇', text: '时令水果' },
  { icon: '🥬', text: '新鲜蔬菜' },
  { icon: '🥚', text: '肉禽蛋类' },
  { icon: '🦐', text: '海鲜水产' },
  { icon: '🏷️', text: '粮油调味' },
  { icon: '🧁', text: '乳品烘焙' },
]

// 定义商品类型
interface Product {
  id: string
  title: string
  image: string
  currentPrice: number
  originalPrice: number
  sales?: number
  stock?: number
  description?: string
  unit?: string
  category?: string
  tags?: string[]
  activity?: string[]
  status?: string
  createdAt?: string
  updatedAt?: string
}

// 购物车商品类型
interface CartItem {
  id: string;
  title: string;
  image: string;
  currentPrice: number;
  originalPrice: number;
  quantity: number;
  category: string;
  tags?: string[];
  activity?: string[];
  stock: number;
  selected: boolean;
}

export default function Home() {
  const [adImages, setAdImages] = useState<string[]>([]);
  const [flashSaleProducts, setFlashSaleProducts] = useState<Product[]>([])
  const [groupBuyProducts, setGroupBuyProducts] = useState<Product[]>([])
  const [isLoadingProducts, setIsLoadingProducts] = useState(false)
  const [showShareDialog, setShowShareDialog] = useState(false);
  const navigate = useNavigate()
  const qrRef = useRef(null);

  const fetchFlashSaleProducts = async () => {
    try {
      setIsLoadingProducts(true)
      const response = await axios.get('http://localhost:3000/jjx/getseckillproducts')
      if (response.data.code === 200) {
        console.log('限时秒杀商品：', response.data.data)
        // 过滤掉禁用状态的商品
        const activeProducts = (response.data.data || []).filter((product: Product) =>
          product.status === 'active'
        )
        setFlashSaleProducts(activeProducts)
      }
    } catch (error) {
      console.error('获取秒杀商品失败:', error)
      Toast.show('获取秒杀商品失败')
    } finally {
      setIsLoadingProducts(false)
    }
  }

  // 获取拼团商品数据
  const fetchGroupBuyProducts = async () => {
    try {
      const response = await axios.get('http://localhost:3000/jjx/getgroupproducts',)
      if (response.data.code === 200) {
        console.log('特惠拼团商品：', response.data.data)
        // 过滤掉禁用状态的商品
        const activeProducts = (response.data.data || []).filter((product: Product) =>
          product.status === 'active'
        )
        setGroupBuyProducts(activeProducts)
      }
    } catch (error) {
      console.error('获取拼团商品失败:', error)
      Toast.show('获取拼团商品失败')
    }
  }

  // 获取广告图片
  useEffect(() => {
    axios.get('http://localhost:3000/jjx/getlunbo').then(res => {
      if (res.data && res.data.code === 200) {
        // 只取上线且首页轮播图的广告
        const imgs = (res.data.data || [])
          .filter((ad: any) => ad.status === '上线' && ad.position === '首页轮播图')
          .map((ad: any) => {
            if (!ad.image) return '';
            if (ad.image.startsWith('http') || ad.image.startsWith('data:image')) return ad.image;
            // 如果是文件名，自动补全
            if (!ad.image.startsWith('/upload/products/')) return 'http://localhost:3000/upload/products/' + ad.image;
            return 'http://localhost:3000' + ad.image;
          });
        setAdImages(imgs);
      }
    });
  }, []);

  useEffect(() => {
    fetchFlashSaleProducts()
    fetchGroupBuyProducts()
  }, [])

  // 只弹出自定义分享弹窗
  const handleShareImage = () => {
    setShowShareDialog(true);
  };

  // 保存二维码为图片
  const handleSaveQRCode = () => {
    const svg = qrRef.current;
    if (!svg) {
      Toast.show('二维码未生成');
      return;
    }
    const serializer = new window.XMLSerializer();
    const svgStr = serializer.serializeToString(svg);
    const img = new window.Image();
    img.src = 'data:image/svg+xml;base64,' + window.btoa(unescape(encodeURIComponent(svgStr)));
    img.onload = () => {
      const canvas = document.createElement('canvas');
      canvas.width = 120;
      canvas.height = 120;
      const ctx = canvas.getContext('2d');
      if (!ctx) {
        Toast.show('保存失败，浏览器不支持canvas');
        return;
      }
      ctx.drawImage(img, 0, 0);
      const url = canvas.toDataURL('image/png');
      const a = document.createElement('a');
      a.href = url;
      a.download = 'qrcode.png';
      a.click();
      Toast.show('二维码已保存');
    };
  };

  const items = adImages.map((image, index) => (
    <Swiper.Item key={index}>
      <div
        className={styles.content}
        onClick={() => {
          Toast.show(`你点击了广告 ${index + 1}`)
        }}
      >
        <img src={image} alt={`广告${index + 1}`} className={styles.bannerImage} />
      </div>
    </Swiper.Item>
  ));

  const handleCategoryClick = (category: { text: string }) => {
    navigate(`/app/class?category=${category.text}`)
  }

  return (
    <div className={styles.home}>
      <div className={styles.header}>
        <img src="/logoo.png" alt="logo" className={styles.logo} />
        <Input placeholder='请输入搜索关键词' className={styles.searchBar} onClick={() => {
          navigate('/app/shou')
        }} />
      </div>
      <div className={styles.locationBar}>
        <div className={styles.location} onClick={() => {
          navigate('/app/xiugaidingwei')
        }}>
          <LocationOutline /> 万达广场店 <RightOutline />
        </div>
        <Button
          color="primary"
          fill="none"
          style={{ marginLeft: 'auto' }}
          onClick={handleShareImage}
        >
          分享
        </Button>
      </div>
      {/* 分享弹窗 */}
      <Dialog
        visible={showShareDialog}
        onClose={() => setShowShareDialog(false)}
        content={
          <div style={{ position: 'relative', padding: 0, background: 'white', borderRadius: 12 }}>
            {/* 右上角关闭按钮 */}
            <div style={{ position: 'absolute', top: 12, right: 12, zIndex: 10, cursor: 'pointer', fontSize: 24 }} onClick={() => setShowShareDialog(false)}>
              ×
            </div>
            {/* 顶部品牌logo */}
            <div style={{
              background: 'linear-gradient(180deg, #ff5a2a 0%, #ffb199 100%)',
              padding: '20px 0 10px 0',
              textAlign: 'center',
              borderTopLeftRadius: 12,
              borderTopRightRadius: 12
            }}>
              <img src="/logoo.png" alt="logo" style={{ height: 32, marginBottom: 8 }} />
              <div style={{ color: '#fff', fontWeight: 'bold', fontSize: 20 }}>社区团购</div>
            </div>
            {/* 广告图片（可选） */}
            {/* <div style={{ textAlign: 'center', margin: '16px 0' }}>
              <img src={adImages[0]} alt="分享图片" style={{ width: 180, borderRadius: 8 }} />
            </div> */}
            {/* 文案 */}
            <div style={{ textAlign: 'center', fontWeight: 'bold', fontSize: 18, marginBottom: 8 }}>今日下单 次日自提</div>
            <div style={{ textAlign: 'center', color: '#666', marginBottom: 16 }}>提货点：菜鸟驿站万达店</div>
            {/* 二维码 */}
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', marginBottom: 16 }}>
              <QRCodeSVG value={window.location.href} size={120} ref={qrRef} />
              <div style={{ fontSize: 13, color: '#333', marginTop: 8 }}>长按识别二维码访问本页</div>
            </div>
            {/* 保存图片按钮 */}
            <Button color="primary" block style={{ borderRadius: 0, marginTop: 8 }} onClick={handleSaveQRCode}>
              保存图片
            </Button>
          </div>
        }
      />
      <div className={styles.banner}>
        <Swiper loop autoplay>
          {adImages.length === 0 ? (
            <Swiper.Item>
              <div className={styles.content}>暂无广告</div>
            </Swiper.Item>
          ) : (
            adImages.map((image, index) => (
              <Swiper.Item key={index}>
                <div className={styles.content}>
                  <img src={image} alt={`广告${index + 1}`} className={styles.bannerImage} />
                </div>
              </Swiper.Item>
            ))
          )}
        </Swiper>
      </div>
      <div className={styles.categories}>
        <Grid columns={6}>
          {categories.map((category, index) => (
            <Grid.Item key={index} onClick={() => handleCategoryClick(category)}>
              <div className={styles.categoryItem}>
                <div className={styles.categoryIcon}>{category.icon}</div>
                <div className={styles.categoryText}>{category.text}</div>
              </div>
            </Grid.Item>
          ))}
        </Grid>
      </div>
      <div className={styles.flashSale}>
        <div className={styles.flashSaleHeader}>
          <div className={styles.flashSaleTitle}>
            <span>限时秒杀</span>
            <span className={styles.flashSaleTime}>01 : 23 : 09</span>
          </div>
          <div className={styles.flashSaleMore} onClick={() => {
            navigate('/xian')
          }}>
            查看全部 <RightOutline />
          </div>
        </div>
        <div className={styles.flashSaleProducts}>
          {flashSaleProducts.map(product => (
            <div key={product.id} className={styles.flashSaleProduct}>
              <div className={styles.productImage}>
                <img src={product.image} alt={product.title} />
              </div>
              <div className={styles.productName}>{product.title}</div>
              <div className={styles.productPrice}>
                <span className={styles.currentPrice}>¥{product.currentPrice}</span>
                <span className={styles.originalPrice}>¥{product.originalPrice}</span>
              </div>
              <Button
                className={styles.addToCartButton}
                onClick={() => {
                  // 添加到购物车
                  const cartItem = {
                    id: product.id,
                    title: product.title,
                    image: product.image,
                    currentPrice: product.currentPrice,
                    originalPrice: product.originalPrice,
                    quantity: 1,
                    category: product.category || '',
                    tags: product.tags || [],
                    activity: product.activity || [],
                    stock: product.stock || 10,
                    selected: true
                  };

                  // 从 localStorage 获取现有购物车
                  const existingCart = localStorage.getItem('cart');
                  let cartItems = existingCart ? JSON.parse(existingCart) : [];

                  // 检查商品是否已在购物车中
                  const existingItemIndex = cartItems.findIndex((item: CartItem) => item.id === product.id);

                  if (existingItemIndex >= 0) {
                    // 如果已存在，增加数量
                    cartItems[existingItemIndex].quantity += 1;
                  } else {
                    // 如果不存在，添加新商品
                    cartItems.push(cartItem);
                  }

                  // 保存到 localStorage
                  localStorage.setItem('cart', JSON.stringify(cartItems));

                  Toast.show('已添加到购物车');
                  navigate('/app/cars');
                }}
              >
                加入购物车
              </Button>
            </div>
          ))}
        </div>
      </div>
      <div className={styles.groupBuy}>
        <div className={styles.groupBuyHeader}>
          <div className={styles.groupBuyTitle}>
            <span>特惠拼团</span>
            <span className={styles.groupBuyCount}>已拼团{groupBuyProducts.length > 0 ? groupBuyProducts[0].sales || 0 : 0}件</span>
          </div>
          <div className={styles.groupBuyMore} onClick={() => {
            navigate('/pin')
          }}>
            查看全部 <RightOutline />
          </div>
        </div>
        <div className={styles.groupBuyProducts}>
          {groupBuyProducts.map(product => (
            <div key={product.id} className={styles.groupBuyProduct}>
              <div className={styles.productImage}>
                <img src={product.image} alt={product.title} />
              </div>
              <div className={styles.productInfo}>
                <div className={styles.groupTag}>3人团</div>
                <div className={styles.productName}>{product.title}</div>
                <div className={styles.groupPrice}>
                  <span className={styles.priceLabel}>拼团价:</span>
                  <span className={styles.currentPrice}>¥{product.currentPrice}</span>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {isLoadingProducts && (
        <div className={styles.loadingOverlay}>
          <SpinLoading color='primary' />
          <span className={styles.loadingText}>加载中...</span>
        </div>
      )}


    </div>
  )
}
